package com.ftar.urgent.util;

import android.text.TextUtils;
import android.util.Log;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @author: wei.jin
 * @date: 2023/7/10
 * @email: wei.jin@fanttec.com
 * @description：
 */
public class StringCompareUtil {
    private static String TAG = StringCompareUtil.class.getSimpleName();
    /**
     * 比较两个字符串的相识度
     * 核心算法：用一个二维数组记录每个字符串是否相同，如果相同记为0，不相同记为1，每行每列相同个数累加
     * 则数组最后一个数为不相同的总数，从而判断这两个字符的相识度
     *
     * @param str
     * @param target
     * @return
     */
    private static int compare(String str, String target) {
        int d[][];              // 矩阵
        int n = str.length();
        int m = target.length();
        int i;                  // 遍历str的
        int j;                  // 遍历target的
        char ch1;               // str的
        char ch2;               // target的
        int temp;               // 记录相同字符,在某个矩阵位置值的增量,不是0就是1
        if (n == 0) {
            return m;
        }
        if (m == 0) {
            return n;
        }
        d = new int[n + 1][m + 1];
        // 初始化第一列
        for (i = 0; i <= n; i++) {
            d[i][0] = i;
        }
        // 初始化第一行
        for (j = 0; j <= m; j++) {
            d[0][j] = j;
        }
        for (i = 1; i <= n; i++) {
            // 遍历str
            ch1 = str.charAt(i - 1);
            // 去匹配target
            for (j = 1; j <= m; j++) {
                ch2 = target.charAt(j - 1);
                if (ch1 == ch2 || ch1 == ch2 + 32 || ch1 + 32 == ch2) {
                    temp = 0;
                } else {
                    temp = 1;
                }
                // 左边+1,上边+1, 左上角+temp取最小
                d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + temp);
            }
        }
        return d[n][m];
    }


    /**
     * 获取最小的值
     */
    private static int min(int one, int two, int three) {
        return (one = one < two ? one : two) < three ? one : three;
    }

    /**
     * 获取两字符串的相似度
     */
    public static float getRatio(String str, String target) {
        int max = Math.max(str.length(), target.length());
        return 1 - (float) compare(str, target) / max;
    }

    //统计字符串有多少个字符
    public static int getStringCount (String str) {
        if (str == null || str.length() == 0) {
            return 0;
        }
        int count = 0;
        char[] chs = str.toCharArray();
        for (int i = 0; i < chs.length; i++) {
            count += (chs[i] > 0xff) ? 2 : 1;
        }
        return count / 2;
    }

    private static boolean hasKeywordsRatio(String str, List<String> keywords) {
        boolean keywordCompareFlag = true;

        for(String item : keywords) {
            if(str.indexOf(item) < 0) {
                keywordCompareFlag = false;
                break;
            }
        }

        return keywordCompareFlag;
    }

    /**
     * 获取两字符串的错读和漏读
     * @param str   结果字符
     * @param target   对比目标字符
     * @param wrongWords  错读列表
     */
    public static void getLostAndWrongWords(String str, String target, List<String> wrongWords) {
        if(TextUtils.isEmpty(str)) {
            return;
        }

        str = filtration(str);
        target = filtration(target);

        int strLength = getStringCount(str);
        int targetLength = getStringCount(target);

        for(int i = 0; i < strLength; i++) {
            String srcStr = str.substring(i, i+1);
            int pos = -1;
            for(int j = 0; j < targetLength; j++) {
                String desStr = target.substring(j, j+1);
                if(desStr.equals(srcStr)) {
                    pos = j;
                    break;
                }
            }
            if(pos != -1) {

            }else {
                wrongWords.add(srcStr);
            }
        }

        return ;
    }


    /**
     * 获取两字符串的相似度
     */
    public static int getSimilarityPosition(String str, String target, final float compareRatio) {
        int pos = -1;

        if(TextUtils.isEmpty(str)) {
            return pos;
        }

        str = filtration(str);
        target = filtration(target);

        pos = 0;
        int startPos = 0;
        float ratio = 0;
        float maxRatio = 0;
        int strLength = getStringCount(str);
        int targetLength = getStringCount(target);

        int firstLength = strLength > targetLength ? targetLength : strLength;
        String srcStr = str.substring(startPos, firstLength);
        maxRatio = getRatio(srcStr, target);

        startPos++;
        while((startPos + targetLength) < strLength) {
            Log.e(TAG, "Compare str：" + str + " length:" + strLength + "  targetLength:" + targetLength + "  startPos:" + startPos);
            srcStr = str.substring(startPos, startPos+targetLength);
            ratio = getRatio(srcStr, target);

            if(maxRatio < ratio ) {
                pos = startPos;
                maxRatio = ratio;
            }
            startPos++;
        }
        Log.e(TAG, "Compare: =============================== compareRatio" + pos);

        return pos;
    }


    /**
     * 获取两字符串的相似度
     */
    public static float getSimilarityRatio(String str, String target, List<String> keywords) {
        float compareRatio = 0.0f;

        if(TextUtils.isEmpty(str) || TextUtils.isEmpty(target)) {
            return compareRatio;
        }

        str = filtration(str);
        target = filtration(target);

        int startPos = 0;
        int strLength = getStringCount(str);
        int targetLength = getStringCount(target);

        int firstLength = strLength > targetLength ? targetLength : strLength;
        String srcStr = str.substring(startPos, firstLength);
        compareRatio = getRatio(srcStr, target);
        if(!hasKeywordsRatio(srcStr, keywords)) {
            compareRatio = 0;
        }

        startPos++;
        while((startPos + targetLength) < strLength) {
            Log.e(TAG, "Compare str：" + str + " length:" + strLength + "  targetLength:" + targetLength + "  startPos:" + startPos);
            srcStr = str.substring(startPos, startPos+targetLength);
            float ratio = getRatio(srcStr, target);

            if(!hasKeywordsRatio(srcStr, keywords)) {
                ratio = 0;
            }

            if(compareRatio < ratio ) {
                compareRatio = ratio;
            }
            startPos++;
        }
        Log.e(TAG, "Compare: =============================== compareRatio" + compareRatio);

        return compareRatio;
    }


    /**
     * 常见特殊字符过滤
     *
     * @param str
     * @return
     */
    public static String filtration(String str) {
        String regEx = "[`~!@#$%^&*()+=|{}:;\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}" +
                "\\u3002|\\uff1f|\\uff01|\\uff0c|\\u3001|\\uff1b|\\uff1a|\\u201c|\\u201d|\\u2018|\\u2019|\\uff08|\\uff09" +
                "|\\u300a|\\u300b|\\u3008|\\u3009|\\u3010|\\u3011|\\u300e|\\u300f|\\u300c|\\u300d|\\ufe43|\\ufe44|\\u3014|\\u3015|\\u2026|\\u2014|\\uff5e|\\ufe4f|\\uffe5|\\uff0d \\uff3f|\\u002d]?";
        str = Pattern.compile(regEx).matcher(str).replaceAll("").trim();
        Log.d(TAG, "str ======" + str + ".");

        return str;
    }
}
